package client.communication;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	private int port;
	private String address;
	
	private static int timeToRetry = 3000;
	private static int triesToRunPlugins = 1; //if lesser than 1, it won't start at all
	private static boolean pluginsStarted = false;
	
	public Client(String address, int port)
	{
		this.port = port;
		this.address = address;
	}
	
	public void startConversation()
	{
		
		int triesCounter = 0;
		while (true)
		{
			System.out.println("Starting connection with server");
			try
			{
				socket = new Socket(address, port);
				socket.setSoTimeout(30000);
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				out = new PrintWriter(socket.getOutputStream(), true);
				MessageProcessor.out = this.out;
				MessageProcessor.in = this.in;
				triesCounter = 0;
			}
			catch (UnknownHostException e)
			{
				System.err.println("ERROR: Unknown host");
				if (triesCounter <= triesToRunPlugins)
					triesCounter++;
			}
			catch (Exception e)
			{
				System.err.println("ERROR: Unable to estabilish connection");
				if (triesCounter <= triesToRunPlugins)
					triesCounter++;
			}
			
			if (triesToRunPlugins > 0 && triesCounter == triesToRunPlugins && !pluginsStarted)
			{
				pluginsStarted = true;
				MessageProcessor.runPlugins();
			}
			else if (triesCounter == 0) // it means that you're actually connected
			{
				System.out.println("Listening for messages");
				String input;
				MessageProcessor msSpec = new MessageProcessor();
				try //-------------------------------------------------------------------------processing the message
				{
					while ((input = in.readLine()) != null)
					{
						if (input.startsWith("get") || input.startsWith("p:"))
						{
							msSpec.process(input);
						}
						else
						{
							System.out.println("INPUT: "+input);
							MessageProcessorThread t = new MessageProcessorThread(socket,input);
							t.start();
						}
					}
				}
				catch(Exception e)
				{
					System.err.println("Connection lost");
				}
			}
			System.out.println("Retrying to estabilish connection in " + (timeToRetry/1000) + " seconds");
			try
			{
				Thread.sleep(timeToRetry);
			}
			catch(Exception e)
			{
				System.err.println("Client thread is unable to sleep");
			}
		}
	}
}
